from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import City, DataCenter, Host, HostPassword, CityHostStatistics, IDCHostStatistics
from .serializers import (
    CitySerializer,
    DataCenterSerializer,
    HostSerializer,
    HostPasswordSerializer,
    HostStatisticSerializer, CityHostStatisticsSerializer, IDCHostStatisticsSerializer
)
import subprocess


class CityViewSet(viewsets.ModelViewSet):
    queryset = City.objects.all()
    serializer_class = CitySerializer


class DataCenterViewSet(viewsets.ModelViewSet):
    queryset = DataCenter.objects.all()
    serializer_class = DataCenterSerializer


class HostViewSet(viewsets.ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer

    @action(detail=True, methods=['get'])
    def check_reachable(self, request, pk=None):
        host = self.get_object()
        try:
            # param = '-n' if platform.system().lower() == 'windows' else '-c'
            # command = ['ping', param, '1', ip_address]
            result = subprocess.run(
                ['ping', '-c', '1', host.ip_address],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            reachable = result.returncode == 0
            return Response({'reachable': reachable})
        except Exception as e:
            return Response(
                {'error': str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class HostPasswordViewSet(viewsets.ModelViewSet):
    queryset = HostPassword.objects.all()
    serializer_class = HostPasswordSerializer
    http_method_names = ['get', 'put', 'patch']


class CityHostStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = CityHostStatistics.objects.all().order_by('-date', 'city__name')
    serializer_class = CityHostStatisticsSerializer

class IDCHostStatisticsViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = IDCHostStatistics.objects.all().order_by('-date', 'idc__city__name', 'idc__name')
    serializer_class = IDCHostStatisticsSerializer